package cn.yiyuan.org.controller;

import cn.yiyuan.base.until.AjaxResult;
import cn.yiyuan.base.until.PageInfo;
import cn.yiyuan.org.domain.Dep;
import cn.yiyuan.org.query.DepQuery;
import cn.yiyuan.org.service.IDepService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @user m
 * @project system
 * @date 2023-10-27
 * @package cn.yiyuan.org.controller
 */
@RestController
@RequestMapping("/dep")
public class DepController {
//注入service
    @Autowired
    private IDepService service;
//restful风格

    /*
                以后 只要看到400 的状态码 那么就说明 你的数据格式不是后台所期望的 参数类型错误
                post和put请求，如果接收的是参数的时候，必须加上注解  RequestBody，  才能获取到值
     */

//新增  修改
@PutMapping
    public AjaxResult insertOrUpdate(@RequestBody Dep dep){
        try {
            if (Objects.isNull(dep.getId())){
                service.insert(dep);
            }else{
                service.update(dep);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

//删除
@DeleteMapping("/{id}")
public AjaxResult delete(@PathVariable("id")Long id){
    try {
       service.delete(id);
        return AjaxResult.success();
    } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.error();
    }
}

//查询
@GetMapping()
public AjaxResult getAll(){
    try {
        return AjaxResult.success(service.getAll());
    } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.error();
    }
}
//根据id查
@GetMapping("/{id}")
public AjaxResult getId(@PathVariable("id") Long id){
    try {
        return AjaxResult.success(service.getById(id));
    } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.error();
    }
}

//分页查询
@PostMapping
    public AjaxResult queryPage(@RequestBody DepQuery depQuery){
        try {
            PageInfo<Dep> pageInfo = service.queryPage(depQuery);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }


}
